<!DOCTYPE html>
<html >
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="../plugins/layui/css/layui.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/layui/css/style.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../layuiadmin/style/admin.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/zTree/css/metroStyle/metroStyle.css?v=${.Config.basic.version}">
    <link rel="stylesheet" href="../plugins/toastr/toastr.min.css?v=${.Config.basic.version}">
    <link rel="stylesheet" href="../plugins/font-awesome-4.7.0/css/font-awesome.min.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="//at.alicdn.com/t/font_2575369_9n08winu4t8.css?spm=a313x.7781069.1998910419.40&file=font_2575369_9n08winu4t8.css" media="all">
    <link rel="stylesheet" href="../css/ztree.css?v=${.Config.basic.version}" media="all">
    <style>
        .layui-fluid {
            padding: 15px;
        }
        .contextmenu {
            border-bottom: 0;
            background: #4958b9;
            position: absolute;
            list-style: none;
            margin: 0;
            padding: 0;
            display: none;
            z-index: 99999;
        }

        .contextmenu li{
            width: 160px;
        }

        .contextmenu li a {
            display: block;
            padding: 5px 20px;
            border-bottom: 1px solid #aaaaaa21;
            cursor: pointer;
            color: #fff;
        }
        .contextmenu li a:hover {
            background: #0f1644;
            color: #fff;
        }
        .toolbar{
            /*text-align: right;*/
            background: #fff;
        }

        .layui-card-body {
            position: relative;
            /*padding: 0;*/
            line-height: 24px;
        }
        .left-content .bg{
            width: 100%;
            height: 100%;
            background: url("/img/base/bg.png") no-repeat;
            background-size:100% 100%;
        }

        .left-content .root_block{
            width: 100%;
            height: 100%;
            background-color: #ccc;
        }

        .left-content .net_group_block{
            width: 100%;
            height: 100%;
            /*background-color: #f2f2f2;*/
        }
        .left-content .net_node_block{
            width: 100%;
            height: 100%;
            /*background-color: #f2f2f2;*/
        }
        .left-content .net_rack_block{
            width: 100%;
            height: 100%;

        }

        .scroll{
            overflow: auto;
        }
        .layui-form-select dl {
            max-height: 150px;
        }
    </style>
    <style>
        .layui-table-view .layui-table td, .layui-table-view .layui-table th {
            padding: 5px 0;
            border-top: 1px solid #404453;
            border-left: 1px solid #404453;
            border-bottom: 1px solid #404453;
            border-right: 1px solid #404453;
        }
    </style>
</head>
<body>
<div class="">
    <div style="display: flex;">
        <div style="width: 380px; ">
            <div class="layui-card tree-div">

                <div class="">
                    <div class=" " >
                        <ul id="treeDemo" class="ztree"></ul>
                    </div>
                </div>
            </div>
        </div>
        <div style="width: calc(100% - 380px);float: right; " >
            <div class="layui-card">

                <div class="layui-card-body">
                    <div class="left-content " >
                        <div class="bg" id="chart"></div>
                        <div style="display: none;" class="root_block">
                        </div>

                        <div style="display: none; " class="house_block">
                            <div class="toolbar">
                                <div class="layui-btn-group" style="float: right">
                                    <button type="button"  onclick="onSave();" class="action-edit layui-btn layui-btn-primary layui-btn-sm"><i class="fa fa-save layui-text-light"></i></button>
                                </div>
                            </div>
                            <blockquote class="layui-elem-quote" id="id-title"></blockquote>
                            <table class="layui-hide" id="table" lay-filter="table"></table>

                        </div>

                    </div>
                </div>

            </div>
        </div>
    </div>
</div>



<script src="../plugins/layui/layui.js"></script>
<script src="../plugins/jquery/jquery-3.6.0.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.core.min.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.excheck.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.exedit.js?v=${.Config.basic.version}"></script>
<script src="../plugins/jquery.slimscroll.min.js"></script>
<script src="../plugins/toastr/toastr.min.js"></script>
<script src="../plugins/moment.min.js"></script>
<script src="../js/utils.js"></script>
<script src="../js/verify.js"></script>
<script src="../js/func.js?v=${.Config.basic.version}"></script>

<script>
    var lay_index=null;
    var zTree=null;
    var table=null;
    var laydate=null;
    var form=null;
    var element=null;
    //var transfer=null;
    var actions=null;
    var token = window.localStorage.getItem("token");
    var user_info=JSON.parse(window.localStorage.getItem("user_info"));
    var func_url="${.func_url}";
    var actions=[];
    var selectedTreeNode=null;
    var menu=null;
    var allData=[];
    var device_define=[];
    //var ac_define=[];
    var users = [];

    var lay_index=null;

    var last_node=null;


    token = 'Bearer ' + token;
    layui.config({
        base: '../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'table','form','iconPicker'], function(){
        $ = layui.$;
        form = layui.form;
        table = layui.table;

        toastr.options = {
            "closeButton": false, //是否显示关闭按钮
            "debug": false, //是否使用debug模式
            "positionClass": "toast-top-center",//弹出窗的位置
            "showDuration": "300",//显示的动画时间
            "hideDuration": "1000",//消失的动画时间
            "timeOut": "2000", //展现时间
            "extendedTimeOut": "1000",//加长展示时间
            "showEasing": "swing",//显示时的动画缓冲方式
            "hideEasing": "linear",//消失时的动画缓冲方式
            "showMethod": "fadeIn",//显示时的动画方式
            "hideMethod": "fadeOut" //消失时的动画方式
        };

        form.verify({
            verify_ip:verify_ip,
        });

        $.ajax({
            type: 'GET',
            url: "../Api/User/List",
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                console.info(res);
                if(res.code>=0){
                    users = res.data;
                }else{
                    layer.alert(res.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载操作信息失败');
            }
        });

        $.ajax({
            type: 'GET',
            url: '../Api/User/Actions',
            data: {func_url:func_url},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                console.info(data)
                actions=data.data;
                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载操作信息失败');
            }
        });

        $.ajax({
            type: 'GET',
            url: '../Api/DeviceDefine',
            data: {},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                console.info(res)
                if(res.code>=0){
                    device_define = res.data;
                    renderSelect();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载设备类型失败');
            }
        });



        $.ajax({
            type: 'GET',
            url: '../Api/User/Actions',
            data: {func_url:func_url},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                console.info(data)
                actions=data.data;
                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载操作信息失败');
            }
        });



        //加载tree
        loadTree();

        resizeElement();
    });

    var tree_setting = {
        view: {
            dblClickExpand: false,
            fontCss: getFont,
            nameIsHTML: true,
        },
        callback: {
            onClick: treeOnClick,
            //onRightClick: OnRightClick,
            //拖拽时鼠标放开事件
            //onDrop: treeOnDrop,
            //beforeDrag: treeBeforeDrag,
            //beforeExpand: zTreeBeforeExpand
            onExpand:treeOnExpand,
            onCollapse:treeOnCollapse
        },
        view: {
            dblClickExpand: false,
            fontCss: getFont,
            nameIsHTML: true,
            //addHoverDom: addHoverDom,
            //removeHoverDom: removeHoverDom,
            //addDiyDom:addHoverDom
        },
        edit: {
            enable: true,
            showRemoveBtn: false,
            showRenameBtn: false,
            drag:{
                autoExpandTrigger: false,
                isCopy: false,
                prev: false,
                next: false,
                inner: false
            }
        },
    };


    function getFont(treeId, node) {
        return node.font ? node.font : {};
    }

    function treeOnClick(event, treeId, treeNode) {
        selectedTreeNode=treeNode;
        resizeElement();
        console.info(selectedTreeNode);
        if(selectedTreeNode.type=="root"){
            $(".left-content").children("div").hide();
            $(".bg").show();
            toastr.info("请选择栏舍");
            //on_view_root();
        } else if(selectedTreeNode.type=="farm"){
            $(".left-content").children("div").hide();
            $(".house_block").show();
            $("#id-title").html(selectedTreeNode.name);
            showDevices();

        }else if(selectedTreeNode.type=="house"){
            $(".left-content").children("div").hide();
            $(".house_block").show();
            $("#id-title").html(selectedTreeNode.name);
            showDevices();
        } else{
            $(".left-content").children("div").hide();
            $(".bg").show();
        }

    }

    function treeOnExpand(event, treeId, treeNode) {
    }

    function treeOnCollapse(event, treeId, treeNode) {
        console.info(treeNode);
    }
    function deepCopy(obj) {
        if (typeof obj != 'object') {
            return obj;
        }
        var newobj = {};
        for (var attr in obj) {
            newobj[attr] = deepCopy(obj[attr]);
        }
        return newobj;
    }

    function renderSelect(){
        //下拉
        var html="<option value='' ></option>";
        for(var i=0;i<device_define.length;i++){
            var selectd="";
            html+="<option "+selectd+" value=\""+device_define[i].device_type+"\">"+device_define[i].device_desc+"</option>";

        }

        $("select[name='device_type']").html(html);


        form.render('select');
    }

    function showDevices() {
        var url="";
        var obj={};
        if(selectedTreeNode.type=="house"){
            url="../Api/House/Users";
            obj={houseid:selectedTreeNode.id};
        }else if(selectedTreeNode.type=="farm"){
            url="../Api/Farm/Users";
            obj={farmid:selectedTreeNode.id};
        }
        $.ajax({
            type: 'GET',
            url: url,
            data: obj,
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                //console.info(data);
                var data =res.data;
                for(var i=0;i<users.length;i++){

                    var user = users[i];
                    user["LAY_CHECKED"]=false;
                    //console.info(user);
                    var matchs = $.grep(data,function (item) {
                        return item.userid==user.userid;
                    });
                    if(matchs.length>0){
                        user["LAY_CHECKED"]=true;

                    }
                }
                //console.info(users);
                table.render({
                    data:users
                    ,elem: '#table'
                    //,url: url
                    ,height: 'full-115'
                    ,method:'GET'
                    ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
                    //,where: obj
                    ,page: false
                    ,limit:30000
                    //,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
                    ,defaultToolbar: ['']
                    ,title: ''
                    ,even:false
                    ,size: 'sm' //小尺寸的表格
                    //,skin: 'nob' //无框风格
                    ,cols: [[
                        {type: 'checkbox', fixed: 'left'}


                        ,{field:'name', title:'用户', sort: false}

                        ,{field:'phone', title:'用户电话', sort: false}
                        ,{field:'role_names', title:'角色',templet: function(d){
                                var html='';
                                if(d.role_names) {
                                    var names = d.role_names.split(',');
                                    for (var i = 0; i < names.length; i++) {
                                        html += "<span class=\"layui-badge layui-bg-black\">" + names[i] + "</span>";
                                    }
                                }
                                return html;
                            }}
                        ,{field:'is_admin', title:'管理员', width:80,align:'center',templet: function(d){
                                var html = "";
                                if(d.is_admin){
                                    html+="<span class=\"layui-badge-dot layui-bg-blue\"></span> "
                                }else{
                                    //html+="<span class=\"layui-badge-dot layui-bg-black\"></span>  离线"
                                }
                                return html;
                            }}

                    ]]
                    ,done: function(res, curr, count){
                        for(var i=0;i<actions.length;i++){
                            $('.action-'+actions[i].action_id).removeClass("layui-hide");
                        }
                        var that = this.elem.next();
                        allData = res.data;
                        res.data.forEach(function (item, index) {
                            //console.log(item.empName);item表示每列显示的数据
                        });
                    }
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载操作信息失败');
            }
        });


    }

    function onSave() {
        console.info(selectedTreeNode);
        var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值
        console.log(checkStatus.data) //获取选中行的数据
        var arr =[];
        var rows = checkStatus.data;
        if(rows.length>0){
            for(var i=0;i<rows.length;i++){
                arr.push(rows[i].userid);
            }
        }
        var userids = arr.join(",");
        var url="";
        var obj={};
        if(selectedTreeNode.type=="house"){
            url="../Api/House/Users";
            obj={houseid:selectedTreeNode.id,userids:userids};
        }else if(selectedTreeNode.type=="farm"){
            url="../Api/Farm/Users";
            obj={farmid:selectedTreeNode.id,userids:userids};
        }
        layer.load(1);
        $.ajax({
            type: 'PUT',
            url: url,
            data: obj,
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            success: function(res){
                if(res){
                    if(res.code>=0){
                        //保存成功
                        toastr.success(res.msg);
                    }else{
                        layer.alert(res.msg);
                    }
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },
            dataType: "json"
        });
    }

    function loadTree() {
        layer.load(1);
        $.ajax({
            type: 'GET',
            url: '../Api/Topo',
            data: {},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                //var data=data.data;
                var nodes=setDataIcon(data.data);
                console.info(nodes);
                zTree = $.fn.zTree.init($("#treeDemo"), tree_setting, nodes);
                //zTree.expandAll(true);
                if(last_node){
                    //修改新增后，默认选中这个节点
                    if(last_node.type=="farm"){
                        var nodes = zTree.getNodesByParam("farmid", last_node.id, null);
                        if(nodes.length>0){
                            const node = nodes[0];
                            console.info(node);
                            zTree.selectNode(node);
                            zTree.setting.callback.onClick(null,null,node);//手动触发onClick事件
                        }
                    }else if(last_node.type=="house"){
                        var nodes = zTree.getNodesByParam("houseid", last_node.id, null);
                        if(nodes.length>0){
                            const node = nodes[0];
                            console.info(node);
                            zTree.selectNode(node);
                            zTree.setting.callback.onClick(null,null,node);//手动触发onClick事件
                        }
                    }
                }else{
                    var nodes = zTree.getNodesByParam("type", "root", null);
                    if(nodes.length>0){
                        const node = nodes[0];
                        console.info(node);
                        zTree.selectNode(node);
                        zTree.setting.callback.onClick(null,null,node);//手动触发onClick事件
                    }
                }

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },
        });

    }


    //设置图标
    function setDataIcon(data){

        for(let i=0; i<data.length; i++){
            var node=data[i];

            node['font']={'color':'#333'};
            if(node.type=='root'){
                node.name = "";
                node["icon"]="../plugins/zTree/css/metroStyle/img/net.png";
                node.isParent=true;
            }
            else if(node.type=='farm'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/location.png";
                node.isParent=true;
                node.open = false;
            }else if(node.type=='house'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/house.png";
                node.isParent=false;
                //node['font']={'color':'#4958b9','font-weight':"bold"};
            }
            if(node['children']){
                var data1=node.children;
                setDataIcon(data1);
            }
        }
        return data;
    }
    $(window).resize(function () {
        //console.info('resize')
        resizeElement();
    });
    function resizeElement() {
        $(".tree-div").slimScroll({
            height: $(window).height()-10,
            size: '4px', //组件宽度
            color: '#eee', //滚动条颜色
            position: 'right', //组件位置：left/right
            distance: '0px', //组件与侧边之间的距离
            start: 'top', //默认滚动位置：top/bottom
            opacity: .4, //滚动条透明度
            alwaysVisible: true, //是否 始终显示组件
            disableFadeOut: false, //是否 鼠标经过可滚动区域时显示组件，离开时隐藏组件
            railVisible: true, //是否 显示轨道
            railColor: '#333', //轨道颜色
            railOpacity: .2, //轨道透明度
            railDraggable: true, //是否 滚动条可拖动
            railClass: 'slimScrollRail', //轨道div类名
            barClass: 'slimScrollBar', //滚动条div类名
            wrapperClass: 'slimScrollDiv', //外包div类名
            allowPageScroll: true, //是否 使用滚轮到达顶端/底端时，滚动窗口
            wheelStep: 10, //滚轮滚动量
            touchScrollStep: 200, //滚动量当用户使用手势
            borderRadius: '7px', //滚动条圆角
            railBorderRadius: '7px' //轨道圆角
        });
    }

</script>

<script src="../js/check_screen.js?v=${.Config.basic.version}"></script>

</body>




</html>